package rabbitmq

import (
	"context"
	amqp "github.com/rabbitmq/amqp091-go"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"golang-sgg-daijia/pkg/log"
)

type MqProducer interface {
	SendMessage(ctx context.Context, exchange, key string, msg []byte) error
}

type mqProducer struct {
	logger *log.Logger
	conn *amqp.Connection
}

func NewRabbitMqProducer(conf *viper.Viper) *amqp.Connection{
	dsn := conf.GetString("data.rabbitmq.dsn")
	conn, err := amqp.Dial(dsn)
	if err != nil {
		panic(err)
	}
	return conn
}

func NewMqProducer(
	conn *amqp.Connection,
	logger *log.Logger,
) MqProducer {
	return &mqProducer{
		logger: logger,
		conn: conn,
	}
}

func (m *mqProducer) SendMessage(ctx context.Context, exchange, key string, msg []byte) error {
	ch, err := m.conn.Channel()
	if err != nil {
		m.logger.Error("mqProducer|SendMessage|Channel", zap.Error(err))
		return err
	}
	defer ch.Close()
	q, err := ch.QueueDeclare(key, false, false, false, false, nil)
	if err != nil {
		m.logger.Error("mqProducer|SendMessage|QueueDeclare", zap.Error(err))
		return err
	}
	err = ch.PublishWithContext(ctx,
		exchange,
		q.Name,
		false,
		false,
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        msg,
		},
	)
	if err != nil {
		m.logger.Error("mqProducer|SendMessage|Publish", zap.Error(err))
		return err
	}
	return nil
}